import pandas as pd
import re
import time
import os
import shutil
from pick_utils import ReMatchFunc, str_plus, isNaNo
from split_utils import special_split, rule_list_1


def classify_1(operate_dir):
    # 读取配置文件 --------------------------------------

    # 检测excel数量，只能放一个，当只有一个excel时，提取它的路径excel_path -------
    print('检查路径下的文件格式...')
    excel_name = None
    excel_count = 0
    file_list = os.listdir(operate_dir)
    for file in file_list:
        if file.endswith('.xlsx') or file.endswith('.xlx'):
            excel_count += 1
            excel_name = file
    if excel_count == 0:
        input('文件夹下没有excel，按任意键退出...')
        raise Exception(0)
    if excel_count > 1:
        input('只能放一个excel，按任意键退出...')
        raise Exception(0)

    # print(excel_name)
    # raise Exception(1212)
    # ----------------------------------------------------------------------
    # print(excel_path)
    # print(img_dir)

    # 读取excel ----------------------------------------
    excel_path = os.path.join(operate_dir, excel_name)
    # print(excel_path)
    try:
        df = pd.read_excel(excel_path)
        df = df.where(df.notnull(), None)
    except Exception as e:
        print(e)
        print('文件不存在或已损坏...')
        input('按任意键退出...')
        raise Exception('123')
    # -------------------------------------------------

    # 备份原始excel表 --------------------------------------------------------------
    print('备份excel...')
    bak_dir = '题名拆分前的备份'
    file_list = os.listdir(operate_dir)
    if bak_dir not in file_list:
        os.makedirs(os.path.join(operate_dir, bak_dir))
    bak_excel_path = os.path.join(os.path.join(operate_dir, bak_dir), excel_name)
    shutil.copyfile(excel_path, bak_excel_path)
    # -----------------------------------------------------------------------------

    new_df = df

    for i in range(df.shape[0]):

        print('{} / {}'.format(i, df.shape[0]))

        try:
            # 读取全部字段 ----------------------------
            nomatch_str = df.loc[i, '[拆分]未匹配到的数据']
            zhengtiming_str = df.loc[i, '[拆分]正题名']
            author_str = df.loc[i, '[拆分]作者']
            fencehao_str = df.loc[i, '[拆分]分册号']
            fenceming_str = df.loc[i, '[拆分]分册名']
            banbenbeizhu_str = df.loc[i, '[拆分]版本备注']
            banbenshuoming_str = df.loc[i, '[拆分]版本说明']
            bind_str = df.loc[i, '[拆分]装帧']
            fujian_str = df.loc[i, '[拆分]附资源']
            kaiben_str = df.loc[i, '[拆分]开本']
            congshuming_str = df.loc[i, '[拆分]丛书名']
            futiming_str = df.loc[i, '[拆分]副题名']
            taozhuangshuliang_str = df.loc[i, '[拆分]套装数量']
            # ---------------------------------------

            # 转list --------------------------------
            nomatch_list = str(nomatch_str).split(';') if not isNaNo(nomatch_str) else None
            zhengtiming_list = str(zhengtiming_str).split(';') if not isNaNo(zhengtiming_str) else None
            author_list = str(author_str).split(';') if not isNaNo(author_str) else None
            fencehao_list = str(fencehao_str).split(';') if not isNaNo(fencehao_str) else None
            fenceming_list = str(fenceming_str).split(';') if not isNaNo(fenceming_str) else None
            banbenbeizhu_list = str(banbenbeizhu_str).split(';') if not isNaNo(banbenbeizhu_str) else None
            banbenshuoming_list = str(banbenshuoming_str).split(';') if not isNaNo(banbenshuoming_str) else None
            bind_list = str(bind_str).split(';') if not isNaNo(bind_str) else None
            fujian_list = str(fujian_str).split(';') if not isNaNo(fujian_str) else None
            kaiben_list = str(kaiben_str).split(';') if not isNaNo(kaiben_str) else None
            congshuming_list = str(congshuming_str).split(';') if not isNaNo(congshuming_str) else None
            futiming_list = str(futiming_str).split(';') if not isNaNo(futiming_str) else None
            taozhuangshuliang_list = str(taozhuangshuliang_str).split(';') if not isNaNo(taozhuangshuliang_str) else None
            # ---------------------------------------

        except Exception as e:
            print(e)
            print('读取对应字段时报错了')
            input('按任意键退出...')
            raise Exception('123')

        # print('------------------------------------------------')
        # print('nomatch_list： {}'.format(nomatch_list))
        # print('zhengtiming_list： {}'.format(zhengtiming_list))
        # print('fencehao_list： {}'.format(fencehao_list))
        # print('fenceming_list： {}'.format(fenceming_list))
        # print('banbenbeizhu_list： {}'.format(banbenbeizhu_list))
        # print('banbenshuoming_list： {}'.format(banbenshuoming_list))
        # print('bind_list： {}'.format(bind_list))
        # print('fujian_list： {}'.format(fujian_list))
        # print('kaiben_list： {}'.format(kaiben_list))
        # print('congshuming_list： {}'.format(congshuming_list))
        # print('futiming_list： {}'.format(futiming_list))
        # print('taozhuangshuliang_list： {}'.format(taozhuangshuliang_list))
        # print('-------------------------------------------------')


        # 归类规则1 --------------------------------------------------
        # 未匹配字段数组只有一个，正题名数组为空，则未匹配字段移动到正题名
        if nomatch_list and len(nomatch_list) == 1:
            if not zhengtiming_list:
                new_df.loc[i, '[拆分]正题名'] = nomatch_list[0]
                new_df.loc[i, '[拆分]未匹配到的数据'] = None
        # ----------------------------------------------------------

        # 归类规则2和3 --------------------------------------------------
        # 未匹配字段数组为空，正题名数组为空，且丛书名数组只有一个，则丛书名移动到正题名
        # 未匹配字段数组为空，正题名数组为空，且丛书名数组有多个，则丛书名数组自身先进行查重，去除重复丛书名，并将第一个丛书名移动到正题名
        if not nomatch_list:
            if not zhengtiming_list:
                if congshuming_list:
                    if len(congshuming_list) == 1:
                        new_df.loc[i, '[拆分]正题名'] = congshuming_list[0]
                        new_df.loc[i, '[拆分]丛书名'] = None
                    elif len(congshuming_list) > 1:
                        congshuming_list = list(set(congshuming_list))   # set用于数组去重,去重后再转为list
                        new_df.loc[i, '[拆分]正题名'] = congshuming_list[0]
                        new_df.loc[i, '[拆分]丛书名'] = ';'.join(congshuming_list[1:])
        # -----------------------------------------------------------

        # 归类规则4 --------------------------------------------------
        # 条件4当[拆分]未匹配到的数据，[拆分]正题名，[拆分]副题名，[拆分]丛书名都为“空”时，默认[拆分]分册名为正题名，需将此列内容归置于字段“[拆分]正题名”下。
        if not nomatch_list:
            if not zhengtiming_list:
                if not futiming_list:
                    if not congshuming_list:
                        if fenceming_list:
                            if len(fenceming_list) == 1:
                                new_df.loc[i, '[拆分]正题名'] = fenceming_list[0]
                                new_df.loc[i, '[拆分]分册名'] = None
                            elif len(fenceming_list) > 1:
                                fenceming_list = list(set(fenceming_list))  # set用于数组去重,去重后再转为list
                                new_df.loc[i, '[拆分]正题名'] = fenceming_list[0]
                                new_df.loc[i, '[拆分]分册名'] = ';'.join(fenceming_list[1:])
        # -----------------------------------------------------------

        # 归类规则5 --------------------------------------------------
        # 条件5当[拆分]未匹配到的数据，[拆分]正题名，[拆分]分册名，[拆分]丛书名都为“空”时，默认[拆分]副题名为正题名，需将此列内容归置于字段“[拆分]正题名”下。
        if not nomatch_list:
            if not zhengtiming_list:
                if not fenceming_list:
                    if not congshuming_list:
                        if futiming_list:
                            if len(futiming_list) == 1:
                                new_df.loc[i, '[拆分]正题名'] = futiming_list[0]
                                new_df.loc[i, '[拆分]副题名'] = None
                            elif len(futiming_list) > 1:
                                futiming_list = list(set(futiming_list))  # set用于数组去重,去重后再转为list
                                new_df.loc[i, '[拆分]正题名'] = futiming_list[0]
                                new_df.loc[i, '[拆分]副题名'] = ';'.join(futiming_list[1:])
        # -----------------------------------------------------------

    # 保存归纳结果 ----------------------------
    new_df.to_excel(excel_path, index=0)
    # ---------------------------------------

if __name__ == '__main__':
    operate_dir = r'C:\Users\cxstar46\Desktop\正则表达式题名拆分测试'
    classify_1(operate_dir)
